package com.yuyou.tas.lesson.service.impl;


import com.yuyou.tas.lesson.mapper.BaseSectionMapper;
import com.yuyou.tas.lesson.mapper.BaseSectionSubjectRelMapper;
import com.yuyou.tas.lesson.mapper.CommDataConfigMapper;
import com.yuyou.tas.lesson.service.IBaseSectionService;
import com.yuyou.tas.lesson.vo.resp.SubjectSections;
import com.yuyou.tas.service.api.admin.entity.AuthUserSection;
import com.yuyou.tas.service.api.admin.entity.CommDataConfig;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseSection;
import com.yuyou.tas.service.api.lesson.entity.BaseSection;
import com.yuyou.tas.service.api.lesson.entity.BaseSectionSubjectRel;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.admin.CommDataConfigEnums;
import com.yuyou.tas.util.enums.lesson.LessonBaseEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import com.yuyou.tas.util.tool.BeanUtils;
import com.yuyou.tas.util.tool.Sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class BaseSectionServiceImpl implements IBaseSectionService {

    @Autowired
    private BaseSectionMapper mapper;

    @Autowired
    private BaseSectionSubjectRelMapper baseSectionSubjectRelMapper;

    @Autowired
    private CommDataConfigMapper dataConfigMapper;

    @Autowired
    private AuthUserAPI authUserAPI;



    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo addSection(String name, Integer isTan,Long pId, LoginRedisObj user,Long organId) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"插入成功");
        BaseSection bs = new BaseSection();
        bs.setId(Sequence.getSequence().nextId());
        bs.setName(name);
        bs.setIsStan(isTan);
        bs.setAuthOrganizationId(organId);
        bs.setCreateTime(new Date());
        bs.setCreateUser(user.getUserId());
        bs.setIsUse(LessonBaseEnums.isEnableed.enabl.getValue());
        bs.setpId(pId);
        bs.setValue(bs.getId());

        //获取最大code值
        Map<String, Object> condion = new HashMap<>();
        condion.put("organ_id",organId);
        condion.put("isUse","1");
        Long maxCode = mapper.findMaxCode(condion);
        bs.setCode(maxCode != null ? (maxCode+1)+"":"1");

        mapper.insert(bs);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo updateSection(String name, Integer isTan,Long pId, Long id) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"更新成功");
        BaseSection bs = new BaseSection();
        bs.setId(id);
        bs.setIsStan(isTan);
        bs.setName(name);
        if(pId != null){
            bs.setpId(pId);
        }
        mapper.updateByPrimaryKeySelective(bs);

        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo delSection(Long id) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"删除成功");
        mapper.deleteByPrimaryKey(id);
        return info;
    }

    @Override
    public ResBoolSimpleInfo<BaseSection> getSectionByID(Long id) {
        BaseSection bs = mapper.selectByPrimaryKey(id);

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,null,bs);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public int findSectionCount(Pagination<DtoBaseSection> queryPgn) {
        return mapper.findSectionCount(queryPgn);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public List<DtoBaseSection> findSectionPageList(Pagination<DtoBaseSection> queryPgn) {
        return mapper.findSectionPageList(queryPgn);
    }

    @Override
    public List<BaseSection> findSectionName(Map<String, Object> condition) {
        return mapper.findSectionName(condition);
    }

    @Override
    public BaseSection selectBaseSectionById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Long> findByIds(Set<Long> ids) {
        List<Long> list = new ArrayList<>();
        if (ids != null && ids.size() > 0){
            Map<String , Object> condtion = new HashMap<>();
            condtion.put("ids",ids);
            condtion.put("is_stan", LessonEnums.type.defind.getValue());
            list = mapper.findByIds(condtion);
        }
        return list;
    }

    @Override
    public BaseSection findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SubjectSections> findBySubject(Map<String, Object> condition) {
        List<SubjectSections> subjectSectionsList = new ArrayList<>();
        List<BaseSectionSubjectRel> list = baseSectionSubjectRelMapper.findSSRs(condition);

        List<BaseSection> sections = findSectionName(condition);//获取标准的年级名称
        Map<Long , BaseSection> sectionMap = BeanUtils.toMap(sections , "id");

        Map<String , Object> s_map = new HashMap<>();//获取科目数据
        s_map.put("category", CommDataConfigEnums.category.subject.getValue());
        List<CommDataConfig> subjects = dataConfigMapper.findSubject(s_map);
        Map<String , CommDataConfig> subjectMap = BeanUtils.toMap(subjects , "id");

        for (BaseSectionSubjectRel ssr : list) {
            List<BaseSection> sectionList = new ArrayList<>();
            String[] sectionIds = ssr.getBaseSectionId().split(",");
            for (String id:sectionIds) {
                sectionList.add(sectionMap.get(Long.valueOf(id)));
            }
            if(!CollectionUtils.isEmpty(sectionList)){//重新排序
                sectionList.sort(Comparator.comparing(section -> section.getSort()));
            }

            SubjectSections ss = new SubjectSections();
            ss.setList(sectionList);
            ss.setSubjectId(ssr.getDataSubject());
            ss.setSubjectName(subjectMap.get(ssr.getDataSubject()).getName());
            subjectSectionsList.add(ss);
        }

        return subjectSectionsList;
    }


    public AuthUserSection getUserSectionBySub(Long userId , Long subjectId){
        return authUserAPI.findSectionByUserIdSubjectId(userId , subjectId);
    }

    @Override
    public List<DtoBaseSection> getUserSection(Long userId , String[] subjectId){
        List<DtoBaseSection> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        Map<String, Object> conditionsMap = new HashMap<>();
        conditionsMap.put("isStan", 1);
        if(subjectId != null && subjectId.length > 0){
            conditionsMap.put("subjectIds", subjectId);
        }
        List<BaseSectionSubjectRel> rels = baseSectionSubjectRelMapper.findSSRs(conditionsMap);
        rels.forEach(r -> {
            if(r.getBaseSectionId() != null){
                String[] ids = r.getBaseSectionId().split(",");
                set.addAll(Arrays.asList(ids));
            }
        });


        if(set.size() > 0 ){
            /*Map<String, Object> conditions = new HashMap<>();
            conditions.put("isStan", 1);
            conditions.put("isUse", 1);*/
//            List<BaseSection> sections = findSectionName(conditions);//获取标准的年级名称
            List<BaseSection> sections = mapper.findBaseSectionFromClass(userId);
//            Map<Long , BaseSection> sectionMap = BeanUtils.toMap(sections , "id");
            for (BaseSection section : sections
                 ) {
                if(set.contains(section.getId().toString())){
                    list.add(new DtoBaseSection(section.getId() , section.getName()));
                }

            }
        }



        return list;
    }

    @Override
    public List<SubjectSections> getUserSectionMap(Long userId , String[] subjectId){
        List<SubjectSections> list = new ArrayList<>();

//        Map<String , Object> s_map = new HashMap<>();//获取科目数据
//        s_map.put("category", CommDataConfigEnums.category.subject.getValue());
        List<CommDataConfig> subjects = dataConfigMapper.findSubjectFromClass(userId);
        Map<Long , CommDataConfig> subjectMap = BeanUtils.toMap(subjects , "id");

        /*Map<String, Object> conditions = new HashMap<>();
        conditions.put("isStan", 1);
        conditions.put("isUse", 1);*/
//        List<BaseSection> sections = findSectionName(conditions);//获取标准的年级名称
        List<BaseSection> sections = mapper.findBaseSectionFromClass(userId);
        Map<Long , BaseSection> sectionMap = BeanUtils.toMap(sections , "id");

        Map<String, Object> conditionsMap = new HashMap<>();
        conditionsMap.put("isStan", 1);
        conditionsMap.put("subjectIds", subjectId);
        List<BaseSectionSubjectRel> rels = baseSectionSubjectRelMapper.findSSRs(conditionsMap);
        Map<Long , BaseSectionSubjectRel> relMap = BeanUtils.toMap(rels , "dataSubject");

        for (String subId:subjectId
                ) {
            SubjectSections sss = new SubjectSections();
            sss.setSubjectId(Long.valueOf(subId));
            sss.setSubjectName(subjectMap.get(Long.valueOf(subId)).getName());
            List<BaseSection> s_list = new ArrayList<>();

            if(relMap.containsKey(Long.valueOf(subId))){
                String[] ids = relMap.get(Long.valueOf(subId)).getBaseSectionId().split(",");
                for (String sId:ids
                        ) {
                    if(sectionMap.containsKey(Long.valueOf(sId))){
                        BaseSection bs = sectionMap.get(Long.valueOf(sId));
                        s_list.add(bs);

                    }
                }
            }

            sss.setList(s_list);
            list.add(sss);

        }

        return list;
    }

    @Override
    public List<BaseSection> findBaseSectionByIds(List<Long> ids) {
        return mapper.findBaseSectionByIds(ids);
    }

    @Override
    public List<DtoBaseSection> getTeachingSection(Long userId, String[] subjectId) {
        List<DtoBaseSection> list = new ArrayList<>();
        Set<String> set = new HashSet<>();
        if(subjectId != null && subjectId.length > 0){
            for (String subId : subjectId){
                AuthUserSection authUserSection = authUserAPI.findSectionByUserIdSubjectId(userId , Long.valueOf(subId));
                if(authUserSection != null && !StringUtils.isEmpty(authUserSection.getBaseSectionId())){
                    set.addAll(Arrays.asList(authUserSection.getBaseSectionId().split(",")));
                }
            }
        }else{
            Set<Long> sections = authUserAPI.findUniSectionByUserId(userId);
            sections.forEach(s -> set.add(s+""));
        }

        if(set.size() > 0 ){
            Map<String, Object> conditions = new HashMap<>();
            conditions.put("isStan", 1);
            conditions.put("isUse", 1);
            List<BaseSection> sections = findSectionName(conditions);//获取标准的年级名称
//            Map<Long , BaseSection> sectionMap = BeanUtils.toMap(sections , "id");
            for (BaseSection section : sections
                    ) {
                if(set.contains(section.getId().toString())){
                    list.add(new DtoBaseSection(section.getId() , section.getName()));
                }

            }
        }

        return list;
    }

    @Override
    public List<SubjectSections> getTeachingSectionMap(Long userId, String[] subjectId) {
        List<SubjectSections> list = new ArrayList<>();

        Map<String , Object> s_map = new HashMap<>();//获取科目数据
        s_map.put("category", CommDataConfigEnums.category.subject.getValue());
        List<CommDataConfig> subjects = dataConfigMapper.findSubject(s_map);
        Map<Long , CommDataConfig> subjectMap = BeanUtils.toMap(subjects , "id");

        Map<String, Object> conditions = new HashMap<>();
        conditions.put("isStan", 1);
        conditions.put("isUse", 1);
        List<BaseSection> sections = findSectionName(conditions);//获取标准的年级名称
        Map<Long , BaseSection> sectionMap = BeanUtils.toMap(sections , "id");

        for (String subId:subjectId
                ) {
            SubjectSections sss = new SubjectSections();
            sss.setSubjectId(Long.valueOf(subId));
            sss.setSubjectName(subjectMap.get(Long.valueOf(subId)).getName());
            List<BaseSection> s_list = new ArrayList<>();

            AuthUserSection authUserSection = authUserAPI.findSectionByUserIdSubjectId(userId , Long.valueOf(subId));

            if(authUserSection != null && !StringUtils.isEmpty(authUserSection.getBaseSectionId())){
                String[] ids = authUserSection.getBaseSectionId().split(",");
                for (String sId:ids
                        ) {
                    if(sectionMap.containsKey(Long.valueOf(sId))){
                        BaseSection bs = sectionMap.get(Long.valueOf(sId));
                        s_list.add(bs);

                    }
                }
            }

            sss.setList(s_list);
            list.add(sss);

        }

        return list;
    }

	@Override
	public List<BaseSection> findAllBaseSection() {
		return mapper.findAllBaseSection();
	}

}